Ext.onReady(function(){
    //Ext.state.Manager.setProvider(new Ext.state.CookieProvider());

    var tabs = Ext.create('Ext.TabPanel', {
        minTabWidth: 115,
        tabWidth:185,
        enableTabScroll:true,
        deferredRender: false,
        autoScroll: false
    });

    function urlConverter(v, record){
       return Ext.supreme.serviceUrlPrefix['t' + record.data.type] + record.data.host
           + record.data.dir + '/' + record.data.name;
    }

    function urlRenderer(url){
        return '<a href="' + url + '"><img src="' + Ext.supreme.downloadIconUrl + '"/></a>';
    }

    function isActiveRenderer(isActive){
        if(isActive)
            return '<img src="' + Ext.supreme.hostIsActiveIcon + '"/></a>';
        else
            return '<img src="' + Ext.supreme.hostIsNotActiveIcon + '"/></a>';
    }

    function addTab(){
        var elem = Ext.get('search_name');
        var store = Ext.create('Ext.data.JsonStore', {
            url: '/ajax/search/files',
            actionMethods: {
                create : 'POST',
                read   : 'POST',
                update : 'POST',
                destroy: 'POST'
            },
            fields: [
                'pk',
                {
                    name:'filename',
                    mapping: 'fields.name',
                    type: 'string'
                },{
                    name:'dirname',
                    mapping: 'fields.dir',
                    type: 'string'
                },{
                    name:'size',
                    mapping: 'fields.size',
                    type: 'int'
                },{
                    name:'host',
                    mapping: 'fields.host',
                    type: 'string'
                },{
                    name:'isActive',
                    mapping: 'fields.isActive',
                    type: 'boolean'
                },{
                    name: 'url',
                    convert: urlConverter
                }
            ]
        });

        var searchResultView = Ext.create('Ext.grid.GridPanel', {
            store: store,
            plugins: new Ext.supreme.SearchResultMenu({
                downloadFileText: 'Pobierz plik',
                downloadSelectedFilesText: 'Pobierz zaznaczone pliki',
                showHostInfoText: 'Pokarz informacje o ho\u015bcie'
            }),
            loadMask:{
                msg:"\u0141aduje dane, proszę czekać...",
                store:store
            },
            columns: [
                {header: "Aktywny", width:5,dataIndex: 'isActive', sortable: true, renderer: isActiveRenderer},
                {header: "Host", width:40,dataIndex: 'host', sortable: true},
                {header: "Katalog", width: 50, dataIndex: 'dirname', sortable: true},
                {header: "Plik", width: 50, dataIndex: 'filename', sortable: true},
                {header: "Rozmiar", width: 10, dataIndex: 'size', sortable: true, renderer: Ext.supreme.filesizeConverter},
                {header: "URL", width:5,dataIndex: 'url', sortable: false, renderer: urlRenderer}
            ],
            viewConfig: {
                forceFit: true
            }
        });

        var tab = tabs.add({
            title: elem.getValue(),
            iconCls: 'tabs',
            layout: 'fit',
            closable: true,
            autoScroll: false,
            items: searchResultView
        })
        tab.show();

        store.load({
            params: getSearchFormVal()
        });
    }

    function getSearchFormVal(){
        return {
            name:Ext.get('search_name').getValue(),
            in_dir:Ext.get('search_in_dir').getValue(),
            modification_date_from:Ext.get('search_modification_date_from').getValue(),
            modification_date_to:Ext.get('search_modification_date_to').getValue(),
            added_to_idx_from:Ext.get('search_added_to_idx_from').getValue(),
            added_to_idx_to:Ext.get('search_added_to_idx_to').getValue(),
            type:Ext.getCmp('search_type').getValue(),
            case_match:Ext.get('search_case_match').getValue(),
            only_active:Ext.get('search_only_active').getValue()
        }
    }

    Ext.regModel('Tokens', {
        fields: [{
                    name:'token',
                    mapping: 'token',
                    type: 'string'
                },{
                    name:'expresion',
                    mapping: 'expresion',
                    type: 'string'
                },{
                    name:'count',
                    mapping: 'resultsCount',
                    type: 'int'
                }]
    });

    var autoCompletion = new Ext.data.Store({
        model: 'Tokens',
        proxy: {
            type: 'ajax',
            url: '/ajax/search/autocomplete',
            noCache: false,
            actionMethods: {
                create : 'POST',
                read   : 'POST',
                update : 'POST',
                destroy: 'POST'
            },
            reader: {
                type: 'json'
            }
        }
    });

    var searchForm = Ext.create('Ext.form.FormPanel', {
        id: 'company-form',
        labelAlign: 'left',
        border: false,
        monitorValid: true,
        items: [{
            xtype: 'fieldset',
            defaults: {
                border: false,
                anchor: '100%'
            },    // Default config options for child items
            defaultType: 'textfield',
            autoHeight: true,
            title: 'Wyszukiwanie',
            //bodyStyle: Ext.isIE ? 'padding:0 0 5px 15px;' : 'padding:10px 15px;',
            border: true,
            style: {
                "margin-left": "10px", // when you add custom margin in IE 6...
                "margin-right": Ext.isIE6 ? (Ext.isStrict ? "-10px" : "-13px") : "0"  // you have to adjust for it somewhere else
            },
            items: [{
                fieldLabel: 'Nazwa',
                xtype: 'combo',
                name: 'text',
                id: 'search_name',
                store: autoCompletion,
                queryMode: 'remote',
                triggerAction: 'all',
                minChars:2,
                valueField: 'token',
                displayField: 'expresion',
                getInnerTpl: function(){
                    return '<tpl for=".">\n\
                        <div class="x-combo-list-item">\n\
                            <div style="display: block; overflow: hidden; ">{token}</div>\n\
                            <div style="display: block; text-align: right; font-style: italic;">Plików: {count} </div>\n\
                        </div>\n\
                    </tpl>';
                },
                emptyText: 'Podaj wyra\u017cenie',
                allowBlank: false,
                hideTrigger:true
            }, {
                xtype: 'combo',
                columns: 1,
                fieldLabel: 'Typ',
                id: 'search_type',
                triggerAction: 'all',
                forceSelection: true,
                typeAhead: true,
                store: new Ext.data.ArrayStore({
                    fields: [
                        'type',
                        'display'
                    ],
                    data: [['all', 'Wszystko'], ['films', 'Filmy'],['music', 'Muzyka'],['graph', 'Grafika'],['apps', 'Programy'],['doc', 'Dokumenty']]
                }),
                valueField: 'type',
                displayField: 'display',
                listeners: {
                    beforerender: function(combo){
                        combo.setValue(combo.store.getAt(0).get('type'));
                    }
                }
            },{
                xtype: 'checkbox',
                fieldLabel: 'Uwzględnij wielkość znaków',
                name: 'case_match',
                checked: false,
                id: 'search_case_match'
            },{
                xtype: 'checkbox',
                fieldLabel: 'Tylko aktywne',
                name: 'only_active',
                checked: false,
                id: 'search_only_active'
            },{
                xtype: 'fieldset',
                defaults: {
                    border: false,
                    anchor: '100%'
                },    // Default config options for child items
                defaultType: 'textfield',
                autoHeight: true,
                title: 'Więcej',
                collapsible: true,
                border: true,
                items:[{
                        xtype: 'checkbox',
                        fieldLabel: 'Szukaj w nazwie\nkatalogu',
                        name: 'in_dir',
                        checked: false,
                        id: 'search_in_dir'
                    },{
                        xtype: 'datefield',
                        fieldLabel: 'Pliki zmodyfikowane\nod',
                        name: 'modification_date_from',
                        id: 'search_modification_date_from'
                    },{
                        xtype: 'datefield',
                        fieldLabel: 'Pliki zmodyfikowane\ndo',
                        name: 'modification_date_to',
                        id: 'search_modification_date_to'
                    },{
                        xtype: 'datefield',
                        fieldLabel: 'Dodane do bazy\npo',
                        name: 'added_to_idx_from',
                        id: 'search_added_to_idx_from'
                    },{
                        xtype: 'datefield',
                        fieldLabel: 'Dodane do bazy\nprzed',
                        name: 'added_to_idx_to',
                        id: 'search_added_to_idx_to'
                    }
                ]
            }]
        }],
        keys:[{
                key: [Ext.EventObject.ENTER],
                handler: addTab
            }
        ],
        buttons:[{
                text: 'Wykonaj',
                id: 'search-button',
                handler: addTab,
                formBind:true
            }]
    });

    Ext.create('Ext.Viewport',{
        layout:{
            type: 'border',
            padding: 5
        },
        items:[{
            region:'east',
            id:'west-panel',
            title:'Panel',
            split:true,
            width: 300,
            minSize: 250,
            maxSize: 500,
            collapsible: true,
            margins:'35 0 5 5',
            cmargins:'35 5 5 5',
            layout: 'auto',
            autoScroll: true,
            items: [buildSideToolbar(), searchForm]
        },{
            region:'center',
            margins:'35 5 5 0',
            layout:'fit',
            autoScroll:false,
            items:[tabs]
        }]
    });

});
